/*
 * @Author: nqx2007 fenglimima334@163.com
 * @Date: 2023-12-04 18:55:03
 * @LastEditors: nqx2007 fenglimima334@163.com
 * @LastEditTime: 2023-12-12 17:57:08
 * @FilePath: /operator-manager/src/pages/Login/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { login } from '@/services';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { history, useModel, useSearchParams } from '@umijs/max';
import { Button, Form, Input } from 'antd';
import { flushSync } from 'react-dom';
import styles from './index.less';
import { LoginFormItem } from './type.d';

export default function LoginPage() {
  const [form] = Form.useForm();
  const [searchParams] = useSearchParams();
  const { initialState, setInitialState } = useModel('@@initialState');
  // 跳转到找回密码
  const handleClick = () => {
    history.push('/find');
  };

  // 进行登录
  const handleToLogin = async () => {
    const values = form.getFieldsValue();
    const result = await login({ data: values });
    if (result?.success) {
      // 登录成功之后存储token，跳转首页
      const { token } = result?.data ?? {};
      localStorage.setItem('token', token);
      localStorage.setItem('userInfo', JSON.stringify(result.data));
      // 获取用户信息
      const currentUser = await initialState?.fetchUserInfo?.();
      console.log('登录成功之后获取用户信息', currentUser);
      if (currentUser) {
        flushSync(() => {
          setInitialState((s) => ({
            ...s,
            currentUser,
          }));
        });
      }
      //跳转到登录之前的页面或者首页
      const currentPath = searchParams?.get(`redirect`) ?? '/merchant_home';
      history.replace(currentPath);
    }
  };
  return (
    <div className={styles.loginContainer}>
      <div className={styles.loginContent}>
        <div className={styles.platName}>
          万券惠
          <br />
          商家管理后台
        </div>
        <div className={styles.formWrapper}>
          <div className={styles.formName}>登录</div>
          <Form form={form}>
            <Form.Item name={LoginFormItem.USER} label="">
              <Input
                autoComplete="current-user"
                addonBefore={<UserOutlined />}
                placeholder="请输入用户名"
              />
            </Form.Item>
            <Form.Item name={LoginFormItem.PASSWORD} label="">
              <Input.Password
                autoComplete="current-password"
                addonBefore={<LockOutlined />}
                placeholder="请输入密码"
              />
            </Form.Item>
            <Form.Item>
              <Button block type="primary" onClick={handleToLogin}>
                登录
              </Button>
            </Form.Item>
            <div className={styles.jumpLink}>
              <a onClick={handleClick}>忘记密码</a>
            </div>
          </Form>
        </div>
      </div>
    </div>
  );
}
